<template>
  <div class="home-container">
    <!-- 顶部统计数据 -->
    <div class="stat-cards">
      <div class="stat-card">
        <div class="stat-title">上报件数</div>
        <div class="stat-value">{{ upkeepNumber }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">待解决</div>
        <div class="stat-value">{{ waitSolve }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-title"> {{ user.position === 0 || user.position === 4 ? "预缴金额(本月)" : "预收金额(本月)"}}</div>
        <div class="stat-value primary-color">{{ collectAdvance }}</div>
      </div>
      <div class="stat-card">
        <div class="stat-title">{{ user.position === 0 || user.position === 4 ? "已缴金额(本月)" : "已收金额(本月)"}}</div>
        <div class="stat-value success-color">{{ received }}</div>
      </div>
    </div>

    <!-- 折线图区域 -->
    <div class="chart-section">
      <div class="chart-header">
        <span>缴费记录</span>
      </div>
      <div class="line-chart-container">
        <div ref="lineChart" class="chart"></div>
      </div>
    </div>

    <!-- 下方图表区域 -->
    <div class="bottom-charts">
      <!-- 饼图 -->
      <div class="chart-box">
        <div class="chart-header">
          <span>车位情况(出售)</span>
        </div>
        <div ref="pieChart" class="chart pie-chart"></div>
      </div>
      
      <!-- 柱状图 -->
      <div class="chart-box">
        <div class="chart-header">
          <span>近七日系统访问记录</span>
        </div>
        <div ref="barChart" class="chart bar-chart"></div>
      </div>
    </div>

    <!-- 通知公告区域 -->
    <div v-if="user.position !== 4 && user.position !== 3" class="notice-section">
      <div class="notice-header">
        <span>小区公告</span>
      </div>
      <div class="notice-list">
        <div class="notice-item" v-for="(item, index) in noticeList" :key="index">
          <div class="notice-content">
            <div class="notice-title"><h3 style="display: block;">标题: {{ item.title }}</h3></div>
            <mavon-editor style="min-height: 10px; max-height: 500px; margin-left: 80px;" v-model="item.content" :subfield="false" :default-open="'preview'" :toolbars-flag="false" :editable="false"/>
          </div>
          <div class="notice-time">{{ item.publishTime }}</div>
        </div>
      </div>
      
      <!-- 分页 -->
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="pageSize"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import api from '@/api';
import { mapState,mapMutations } from "vuex"

export default {
  computed:{
      ...mapState("login",["user"])
    },
  components: {
      mavonEditor,
  },
  data() {
    return {
      paidAmount:[0,0,0,0,0,0,0,0,0,0,0,0],
      unPaidAmount:[0,0,0,0,0,0,0,0,0,0,0,0],
      parkdata:[{ value: 0, name: '出售车位' }, { value: 0, name: '剩余车位' }],
      costStatiesDTOS:[],
      collectAdvance:"",
      received:"",
      upkeepNumber:"",
      waitSolve:"",
      options:[],
      pageSize:3,
      total:10,
      lineChart: null,
      pieChart: null,
      barChart: null,
      // 公告
      noticeList: [
        {
          title: '小区公共设施维修通知',
          content: '尊敬的业主：小区将于2023年7月15日-7月20日对公共设施进行维修，期间可能会影响部分区域的正常使用，请业主们合理安排出行，给您带来的不便敬请谅解。',
          publishTime: '2023-07-10',
        },
        {
          title: '小区消防安全检查通知',
          content: '尊敬的业主：为确保小区安全，物业将于2023年7月25日进行消防安全检查，请各位业主配合工作人员检查工作，保持消防通道畅通，及时清理堆放物品。',
          publishTime: '2023-07-12',
        },
        {
          title: '关于缴纳物业费的通知',
          content: '尊敬的业主：请尚未缴纳2023年度物业费的业主尽快完成缴费，可通过线上支付或到物业服务中心现场缴纳，感谢您的配合。',
          publishTime: '2023-07-15',
        }
      ],
      searchData:{
            keyword: '',
            receiverIds: '',
            startTime: '',
            endTime: '',
            status: 1,
            pageNow: 1,
            pageSize:3
      },
      //近七天数据
      lastSevenDay:[
      ],
      lastSevenDayValue:[
      ]
    }
  },
  created(){
    this.getCostInfoByMonth();
    this.getLastSevenDays()
    this.getNotices();
    this.getCostInfo();
    this.getUpkeepNumber();
  },
  // 窗口大小变化时重新调整图表大小
  mounted() {
    this.initCharts();
    window.addEventListener('resize', this.handleResize);
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.searchData.pageNow = val
      //获取公告信息
      this.getNotices();
    },
    initCharts() {
      this.initLineChart();
      this.initPieChart();
    },
    //获取缴费记录
    getCostInfoByMonth(){
      api.getCostInfoByMonth().then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                  this.costStatiesDTOS = res.data.data.costStatiesDTOS || []
                  
                  this.costStatiesDTOS.forEach(cost =>{
                    this.paidAmount[cost.month - 1] = cost.paidAmount
                    this.unPaidAmount[cost.month - 1] = cost.unPaidAmount
                  })
                  console.log(this.paidAmount)
                  this.initLineChart()
              }else{
                this.$message.error(res.data.message)
              }
      })  
    },

    initLineChart() {
      this.lineChart = echarts.init(this.$refs.lineChart);
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        legend: {
          data: ['已缴纳', '未缴纳']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '已缴纳',
            type: 'line',
            itemStyle: {
              color: '#1890ff' // 蓝色
            },
            lineStyle: {
              width: 3
            },
            symbolSize: 8,
            data: this.paidAmount
          },
          {
            name: '未缴纳',
            type: 'line',
            itemStyle: {
              color: '#f5222d' // 红色
            },
            lineStyle: {
              width: 3,
            },
            symbolSize: 8,
            data: this.unPaidAmount
          }
        ]
      };
      this.lineChart.setOption(option);
    },
    //车位情况
    initPieChart() {
      api.getPark().then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                  this.parkdata = [{ value: res.data.data.uSole, name: '出售车位' }, { value: res.data.data.nSole, name: '剩余车位' }]
                  this.pieChart = echarts.init(this.$refs.pieChart);
                  const option = {
                    tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
                    series: [{
                      name: '车位情况占比(出售)',
                      type: 'pie',
                      radius: ['50%', '70%'],
                      data: this.parkdata,
                    }]
                  };
                  this.pieChart.setOption(option);
              }else{
                this.$message.error(res.data.message)
              }
      })
    },

    //获取近七天日期
    getLastSevenDays() {
      // 获取当前日期
      const currentDate = new Date();
      let recoredDTO = [{}];
      let recordMap = new Map();

      // 获取访问数量
      api.getRecord().then(res => {
          if (res.type === 'error') {
              this.$message.error(res.message);
          } else if (res.data.code === 200) {
              recoredDTO = res.data.data.recoredDTO;
              // 遍历 recoredDTO 数组
              for (let i = 0; i < recoredDTO.length; i++) {
                  let record = recoredDTO[i];
                  // 假设 record 对象有 sunNum 和 recordNum 属性
                  // 确保 sunNum 是字符串类型
                  recordMap.set(String(record.sunNum), record.recordNum);
              }

            // 循环七天
            for (let i = 6; i >= 0; i--) {
                // 创建一个新的日期对象，避免修改原始日期
                const date = new Date(currentDate);
                // 将日期设置为当前日期减去 i 天
                date.setDate(date.getDate() - i);
                // 获取该日期是几号
                const day = date.getDate();
                // 将结果添加到数组中
                this.lastSevenDay.push(day + '号');
                // 获取访问数量
                // 确保 day 是字符串类型
                if (recordMap.get(String(day)) !== undefined) {
                    this.lastSevenDayValue.push({ value: recordMap.get(String(day)) });
                }else {
                    // 如果没有对应的记录，push 默认值
                    this.lastSevenDayValue.push({ value: 0 });
                }
            }
            this.initBarChart()              
          } else {
              this.$message.error(res.data.message);
          }
      });
    },
    initBarChart() {
      this.barChart = echarts.init(this.$refs.barChart);
      const option = {
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        xAxis: [{ type: 'category', data: this.lastSevenDay, axisTick: { alignWithLabel: true } }],
        yAxis: [{ type: 'value' }],
        series: [{
          name: '近七日访问记录',
          type: 'bar',
          barWidth: '60%',
          data: this.lastSevenDayValue
        }]
      };
      this.barChart.setOption(option);
    },
    handleResize() {
      if (this.lineChart) this.lineChart.resize();
      if (this.pieChart) this.pieChart.resize();
      if (this.barChart) this.barChart.resize();
    },
    //查询公告信息
    getNotices() {
        //查询公告信息
        api.noticeList(this.searchData).then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                  this.noticeList = res.data.data.noticeInfoDTO;
                  this.total = res.data.data.total
              }else{
                this.$message.error(res.data.message)
              }
        })
    },
    //获取上报件数以及待解决数
    getUpkeepNumber(){
       api.getUpkeepNumber().then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                  this.upkeepNumber = res.data.data.upkeepNumber
                  this.waitSolve = res.data.data.waitSolve
              }else{
                this.$message.error(res.data.message)
              }
        })
    },
    //获取预/已收金额
    getCostInfo(){
       api.getCostInfo().then(res =>{
              if(res.type === 'error'){
                  this.$message.error(res.message)
              }else if(res.data.code === 200){
                  this.received = res.data.data.received
                  this.collectAdvance = res.data.data.collectAdvance
              }else{
                this.$message.error(res.data.message)
              }
        })
    }    
  },
  // 销毁图表实例，避免内存泄漏
  beforeDestroy() {
      window.removeEventListener('resize', this.handleResize);
      if (this.lineChart) this.lineChart.dispose();
      if (this.pieChart) this.pieChart.dispose();
      if (this.barChart) this.barChart.dispose();
  },
}
</script>

<style scoped>
.home-container {
  height: 400px;
}

/* 统计卡片样式 */
.stat-cards {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  margin-right: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.stat-card:last-child {
  margin-right: 0;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.primary-color {
  color: #3a84ff;
}

.success-color {
  color: #5ad8a6;
}

/* 图表区域样式 */
.chart-section {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.line-chart-container {
  height: 300px;
}

.bottom-charts {
  display: flex;
  margin-bottom: 20px;
}

.chart-box {
  flex: 1;
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.chart-box:first-child {
  margin-right: 15px;
}

.chart {
  height: 300px;
}

.pie-chart {
  height: 300px;
}

.bar-chart {
  height: 300px;
}

/* 通知公告区域样式 */
.notice-section {
  background-color: #fff;
  border-radius: 4px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.notice-header {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 15px;
}

.notice-list {
  margin-bottom: 15px;
}

.notice-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.notice-content {
  flex: 1;
}

.notice-title {
  font-size: 16px;
  color: #303133;
  margin-bottom: 8px;
}

.notice-desc {
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
}

.notice-time {
  width: 100px;
  text-align: right;
  font-size: 14px;
  color: #909399;
}

.notice-checkbox {
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.page-btn, .page-num {
  display: inline-block;
  min-width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  margin: 0 5px;
  border-radius: 2px;
  cursor: pointer;
}

.page-num {
  background-color: #f4f4f5;
  color: #606266;
}

.page-num.active {
  background-color: #3a84ff;
  color: #fff;
}

.page-btn {
  background-color: #f4f4f5;
  color: #606266;
}

.page-btn:hover, .page-num:hover {
  color: #3a84ff;
}

.page-num.active:hover {
  color: #fff;
}
</style>